using System;
using Soundteller.Library.Model;
using Soundteller.Library.Repositories.Interfaces;
using Soundteller.Library.Services.Interfaces;

namespace Soundteller.Library.Services
{
    internal class Metronome : IMetronome
    {
        public event Beat OnBeat;

        private readonly ISongTimeRepository _songTimeRepository;

        public Metronome(ISongTimeRepository songTimeRepository)
        {
            if (songTimeRepository == null) throw new ArgumentNullException("songTimeRepository");

            _songTimeRepository = songTimeRepository;
        }

        public void Tick(double elapsedMilliseconds)
        {
            //var totalElapsedMilliseconds = _songTimeRepository.UpdateElapsedTime(request.ElapsedMilliseconds);
            //var milisecondsPerBeat = CalculateMilliSecondsPerBeat(request.TempoInBpm);

            //var currentBeat = (totalElapsedMilliseconds / milisecondsPerBeat);
            //if (currentBeat >= request.EndLoopBpm)
            //{
            //    currentBeat = 0;
            //    _songTimeRepository.ResetElapsedTime();
            //}

            //_songTimeRepository.UpdateCurrentBeat(currentBeat);

            //if (OnBeat != null) OnBeat(currentBeat);
        }

        public TimeSpan GetEllapsedTime()
        {
            throw new NotImplementedException();
            //var totalElapsedMilliseconds = _songTimeRepository.GetElapsedMilliseconds();
            //return TimeSpan.FromMilliseconds(totalElapsedMilliseconds);
        }

        private double CalculateMilliSecondsPerBeat(double tempoInBpm)
        {
            var beatsPerMillisecond = (tempoInBpm / 60000);
            var milisecondsPerBeat = (1 / beatsPerMillisecond);

            return milisecondsPerBeat;
        }
    }
}
